import { defineStore } from "pinia";
import { AdminLogin } from "../Net/netApi.js";
import http from "../Net/http";
import {LocalClearPro,LocalSave} from '../Util/SaveUtil.js'

export const UserInfoStore = defineStore("UserStore",{
  state: () => {
    return {
      loginStatus: false,
      userInfo: {
        avatar: "/static/images/common/logo.png",
        nickname: "未登录",
        token:''
      },
    };
  },
  actions: {
    login(username, password) {
       AdminLogin(username, password).then((res) => {
        let info = res.data;
        if (res.code == 200) {
          this.loginStatus = true;
          this.userInfo = info;
          ElMessage({
            message: "登录成功",
            type: "success",
          });
        }
      });
    },
    logout() {
      setTimeout(() => {
        this.loginStatus = false;
      }, 1000);

      this.userInfo = {
        avatar: "/static/images/common/logo.png",
        nickname: "未登录",
      };
      LocalClearPro('UserStore').then(res=>{
        ElMessage({
          message: "退出登录成功",
          type: "success",
        });
      }).catch(err=>{
        ElMessage({
          message: "退出行为错误",
          type: "error",
        });
      })
    },
    Persist() {
      let saveData = {
        loginStatus: this.loginStatus,
        userInfo: this.userInfo,
      };
      LocalSave("UserStore", saveData)
        .then((res) => {
          console.log("本地保存成功");
        })
        .catch((err) => {
          console.error("保存失败");
        });
    },
  },
  persist: true,
});
